﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Common;
using Common.Config;
using Common.Model;
using ConsoleService.API;
using ConsoleService.Model;
using HtmlAgilityPack;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLog;
using NLog.Web;
using Quartz;


namespace ConsoleService.Job
{
    /// <summary>
    /// 同步数据，并实现Excute方法
    /// </summary>
    public class CompanyDataJob : IJob
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        public CompanyDataJob()
        {
            NLog.Web.NLogBuilder.ConfigureNLog("nlog.config");
        }

        public Task Execute(IJobExecutionContext context)
        {
            return Task.Run(() =>
            {
                var triggerData = context.Trigger.JobDataMap;//获取Trigger中的参数
                var data = context.MergedJobDataMap;//获取Job和Trigger中合并的参数
                var companyList = JsonConvert.DeserializeObject<List<string>>(triggerData.Get("companyList").ToString());

                CommonAPI commonAPI = new CommonAPI();
                var s = new Stopwatch();
                s.Start();

                var text = $"开始解析数据：{companyList.Count}.....";
                Console.WriteLine(text);
                logger.Warn(text);

                var pageSize = 20;//分页条数
                int j = pageSize;
                for (int i = 0; i < companyList.Count(); i += pageSize)
                {
                    Console.WriteLine($"第{i}页：");
                    var list = companyList.Take(j).Skip(i).ToList();
                    commonAPI.GetSearchCompany(list, false);
                    Thread.Sleep(7000);
                    j += pageSize;
                }

                s.Stop();
                var msg = $"同步公司数据成功用时：{ s.Elapsed.ToString()}" + DateTime.Now.ToString();

                logger.Warn(msg);
                Console.WriteLine(msg);
            });
        }
    }
}
